package com.douyang.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyang.base.expcetion.UserException;
import com.douyang.base.model.Result;
import com.douyang.base.model.UserBaseInfo;
import com.douyang.dto.LoginDTO;
import com.douyang.mapper.UserBaseInfoMapper;
import com.douyang.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service("token")
public class AccessTokenAuthServiceImpl extends ServiceImpl<UserBaseInfoMapper, UserBaseInfo> implements AuthService {

    @Value("${oauth2.url}")
    private String oauth2Url;

    @Autowired
    private RestTemplate restTemplate;
    @Override
    public UserBaseInfo execute(LoginDTO loginDTO) {
        String token = loginDTO.getOauth2AccessToken();
        ResponseEntity<Result<UserBaseInfo>> response = restTemplate.exchange(
                oauth2Url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<Result<UserBaseInfo>>() {},
                Map.of("token",token)
        );
        if (!response.getStatusCode().is2xxSuccessful() ) throw new UserException("token换取失败，code:" + response.getStatusCode());
        Result<UserBaseInfo> result = response.getBody();
        if(result ==null)throw new UserException("token换取失败，无返回体");
        if(result.getCode()!=200)throw new UserException(result.getMsg());
        UserBaseInfo data = result.getData();
        String email = data.getEmail();
        return lambdaQuery().eq(UserBaseInfo::getEmail, email).one();
    }
}
